package com.example.villagedevelop.generator.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.villagedevelop.generator.entity.House;
import com.example.villagedevelop.generator.entity.HouseVO;
import com.example.villagedevelop.generator.entity.ImageHouse;
import com.example.villagedevelop.generator.mapper.HouseMapper;
import com.example.villagedevelop.generator.mapper.ImageHouseMapper;
import com.example.villagedevelop.generator.service.HouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author villagedevelop
 * @since 2021-11-13
 */
@RestController
@RequestMapping("/house")
public class HouseController {

    @Autowired
    HouseMapper mapper;
    @Autowired
    HouseService houseService;
    @Autowired
    ImageHouseMapper imageHouseMapper;

    @GetMapping("/visit")
    public List<HouseVO> findAll(){
        return houseService.findHouseVOByPageAndOrder();
    }//返回所有数据



    @GetMapping("/visitTown")//返回乡镇
    public List<String> findTown(){
        List<House> houseList = houseService.list();
        List<String> towns = new ArrayList<>();
        //去重
        for (House house:houseList) {
            towns.add(house.getTown());
        }
        LinkedHashSet<String> hashSet = new LinkedHashSet<>(towns);
        ArrayList<String> townList = new ArrayList<>(hashSet);
        return townList;
    }//copy ok



    @GetMapping("/deleteImage")
    public void delete(@RequestParam("image") String image){
        QueryWrapper<ImageHouse> wrapper = new QueryWrapper<>();
        wrapper.eq("image_file",image);
        imageHouseMapper.delete(wrapper);
    }//从数据库中删除图片

    @GetMapping("/deleteObject")
    public void delete(int id){
        houseService.deleteObject(id);
    }//根据id删除数据

    @PostMapping("/saveData")
    public int insertData(@RequestBody House house){
        houseService.save(house);
        house.setDefaultSort(house.getId());//设置默认排序与id一样
        houseService.updateById(house);
        return house.getId();
    }//插入数据

    @GetMapping("/changeSort")
    public void changeDefaultSort(@RequestParam("id1") int id1,@RequestParam("id2") int id2){
        houseService.changeDefaultSort(id1, id2);
    }//改变默认排序顺序

    @PostMapping("/saveImages")
    public String upload(int id,MultipartFile img){//request用于获取服务器绝对路径

        if (img.getSize()>0){//判断文件是否为空
            //获取保存文件file路径，将文件保存到tomcat服务器的文件目录下，也可以自己写文件路
//tomcat服务器路径：D:\mytool\apache-tomcat-8.5.65-windows-x64\apache-tomcat-8.5.65\webapps\ROOT
            ///root/static/zhangbei/image
            String path = "D:/picture/image";
            //获取上传的文件名
            String name = img.getOriginalFilename();
            File file = new File(path,name);

            String suffixName = name.substring(name.lastIndexOf("."));
            List<String> extList = Arrays.asList(".jpg", ".JPG",".png", ".jpeg", ".gif");
            if (!extList.contains(suffixName)) {
                return "图片格式非法";
            }

            try {
                img.transferTo(file);//将img保存进file文件
                ImageHouse imageHouse = new ImageHouse();
                String name_random = String.valueOf(System.currentTimeMillis());
                name_random += (int)((Math.random() * 9 + 1)* 10000);
                imageHouse.setImageFile("http://zbnczy.com/image/"+name_random+suffixName);
                imageHouse.setHId(id);
                imageHouseMapper.insert(imageHouse);

                int m = 0;
                //保存上传之后的文件路径，
//                request.setAttribute("path","/file/"+name);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "ok!";
    }

    //修改信息
    @PostMapping("modify")
    public void modify(@RequestBody House house){
        houseService.updateById(house);
    }//copy ok

    @GetMapping("/select/{town}")//根据town返回返回village
    public List<String> selectByTown(@PathVariable("town") String town){
        return houseService.findVillage(town);
    }
    @GetMapping("/select/{town}/1")//根据town返回HouseVO
    public List<HouseVO> selectByTown_village(@PathVariable("town") String town){
        return houseService.findHouseVOBytown(town);
    }
    @GetMapping("/select/{town}/{village}")//根据town和village返回HouseVO
    public List<HouseVO> selectByTown_village(@PathVariable("town") String town,@PathVariable("village") String village){
        return houseService.findHouseVOBytown_village(town,village);
    }

    @GetMapping("/select/{field}/{min}/{max}")//范围查找
    public List<HouseVO> select_Classify(@PathVariable("field") String field,@PathVariable("min") int min,@PathVariable("max") int max){
        return houseService.findHouseVO_Classify(field,min,max);
    }

    /**
     * 排序
     * @param field 查找字段
     * @param method 排序方式
     * @param min
     * @param max
     * @return
     */
    @GetMapping("/select/{field}/{method}/{min}/{max}")//范围查找并排序
    public List<HouseVO> select_Classify(@PathVariable("field") String field,@PathVariable("method") int method,@PathVariable("min") int min,@PathVariable("max") int max){
        return houseService.findHouseVO_Classify_order(field,method,min,max);
    }

    //通过property查询
    @GetMapping("/selectbyproperty/{property}")
    public List<HouseVO> selectByProperty(@PathVariable("property") String property){
        return houseService.findHouseVO_Classify_Property(property);
    }

    //模糊查询
    @GetMapping("/search")
    public List<House> search(String word){
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.like("title",word);
        return mapper.selectList(wrapper);
    }


}

